package com.xiongmm.stream.database;

import com.xiongmm.stream.domain.InstanceInfoAllVo;
import com.xiongmm.stream.domain.InstanceInfoCmdVo;
import com.xiongmm.stream.utils.BambooUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author XiongMM
 * @Date: 2018/6/28 20:02
 * @Description:数据入库操作
 */
public class DataManipulation {

    private static final Logger LOGGER = LoggerFactory.getLogger(DataManipulation.class);

    private static final String CMD_STAT_SQL = "insert into cache_instance_cmd_stat_new " +
            "(app_id,inst_id,command_name,command_count,command_usec,command_type,collect_time,create_time)" +
            "values (?,?,?,?,?,?,?,?)";

    private static final String INSTANCE_STAT_SQL = "insert into cache_instance_stat_new " +
            "(inst_id,app_id,host_id,ip,port,role,max_mem,used_mem,key_count,curr_connections,misses,hits,misses_diff,hits_diff,latest_fork_usec,aof_rewrite_in_progress" +
            ",aof_last_rewrite_time_sec,blocked_clients,rdb_last_bgsave_status,rdb_last_save_time,client_input_buf,client_output_list,master_link_status,master_link_down_since_seconds" +
            ",master_last_io_seconds_ago,connected_slaves,slave_lag,qps,has_expire_key_count,mem_fragmentation_ratio,create_time,collect_time,modify_time) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" +
            "on duplicate key update " +
            "inst_id = values(inst_id) , app_id = values(app_id) , host_id = values(host_id) , ip = values(ip) , port = values(port) ,role = values(role) , max_mem = values(max_mem)," +
            "used_mem = values(used_mem) , key_count = values(key_count) , curr_connections = values(curr_connections) , misses = values(misses) ,hits = values(hits),misses_diff = values(misses_diff)," +
            "hits_diff = values(hits_diff) , latest_fork_usec = values(latest_fork_usec) , aof_rewrite_in_progress = values(aof_rewrite_in_progress) , aof_last_rewrite_time_sec = values(aof_last_rewrite_time_sec) ," +
            "blocked_clients = values(blocked_clients) , rdb_last_bgsave_status = values(rdb_last_bgsave_status) , rdb_last_save_time = values(rdb_last_save_time) , client_input_buf = values(client_input_buf) ," +
            "client_output_list = values(client_output_list) , master_link_status = values(master_link_status) , master_link_down_since_seconds = values(master_link_down_since_seconds) , master_last_io_seconds_ago = values(master_last_io_seconds_ago) ," +
            "connected_slaves = values(connected_slaves) , slave_lag = values(slave_lag) , qps = values(qps),has_expire_key_count = values(has_expire_key_count),mem_fragmentation_ratio = values(mem_fragmentation_ratio),collect_time = values(collect_time) , modify_time = values(modify_time)";


    private static final String INSTANCE_INFO_ALL_SQL = "insert into cache_app_statistic_log_new " +
            "(app_id,inst_id,ip,port,mem_use_percent,used_mem,key_count,has_expire_key_count,expired_key_count,evicted_key_count,expired_keys_diff,evicted_keys_diff,qps,misses_diff,hits_diff,hit_percent," +
            "curr_connections,role,latest_fork_usec,aof_rewrite_in_progress,aof_last_rewrite_time_sec,aof_current_size,aof_base_size,rdb_last_bgsave_status,rdb_last_save_time,client_input_buf,client_output_list," +
            "total_commands_processed_diff,master_link_down_since_seconds,connected_slaves,slave_lag,redis_used_cpu_sys,redis_used_cpu_user,redis_used_cpu_sys_children,redis_used_cpu_user_children,create_time,collect_time) " +
            " values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

    /**
     * info command整合到多少条数据就入库
     */
    private static final List<List<Object>> INFO_CMD_VO_LIST = new ArrayList<>();
    private static final int CMD_INT = 1000;

    /**
     * info all 整合到多少条数据入库
     */
    private static final List<List<Object>> INFO_ALL_VO_LIST = new ArrayList<>();
    private static final int INFO_ALL_INT = 100;

    /**
     * info stat整合到多少条数据就入库
     */
    private static final List<List<Object>> INFO_STAT_LIST = new ArrayList<>();
    private static final int INFO_STAT_INT = 100;

    /**
     * 新增cache_app_statistic_log_new
     *
     * @param infoAllVo
     * @return
     */
    public static void insertInstanceInfoAll(InstanceInfoAllVo infoAllVo) {
        List<Object> params;
        if (infoAllVo != null) {
            params = new ArrayList<Object>();
            params.add(infoAllVo.getAppId());
            params.add(infoAllVo.getInstanceId());
            params.add(infoAllVo.getIp());
            params.add(infoAllVo.getPort());
            params.add(infoAllVo.getMemUsePercent());
            params.add(infoAllVo.getUsedMem());
            params.add(infoAllVo.getKeyCount());
            params.add(infoAllVo.getHasExpireKeyCount());
            params.add(infoAllVo.getExpiredKeyCount());
            params.add(infoAllVo.getEvictedKeyCount());
            params.add(infoAllVo.getExpiredKeysDiff());
            params.add(infoAllVo.getEvictedKeysDiff());
            params.add(infoAllVo.getQps());
            params.add(infoAllVo.getMissesDiff());
            params.add(infoAllVo.getHitsDiff());
            params.add(infoAllVo.getHitPercent());
            params.add(infoAllVo.getCurrConnections());
            params.add(infoAllVo.getRole());
            params.add(infoAllVo.getLatestForkUsec());
            params.add(infoAllVo.getAofRewriteInProgress());
            params.add(infoAllVo.getAofLastRewriteTimeSec());
            params.add(infoAllVo.getAofCurrentSize());
            params.add(infoAllVo.getAofBaseSize());
            params.add(infoAllVo.getRdbLastBgsaveStatus());
            params.add(infoAllVo.getRdbLastSaveTime());
            params.add(infoAllVo.getClientInputBuf());
            params.add(infoAllVo.getClientOutputList());
            params.add(infoAllVo.getTotalCommandsProcessedDiff());
            params.add(infoAllVo.getMasterLinkDownSinceSeconds());
            params.add(infoAllVo.getConnectedSalves());
            params.add(infoAllVo.getSlaveLag());
            params.add(infoAllVo.getRedisUsedCpuSys());
            params.add(infoAllVo.getRedisUsedCpuUser());
            params.add(infoAllVo.getRedisUsedCpuSysChild());
            params.add(infoAllVo.getRedisUsedCpuUserChild());
            params.add(new Date());
            params.add(BambooUtils.getDateFromUnixTime(infoAllVo.getCollectTime()));
            INFO_ALL_VO_LIST.add(params);
        }
        if (INFO_ALL_VO_LIST.size() == INFO_ALL_INT) {
            try {
                OzoMonitorJdbc.batchInsert(INSTANCE_INFO_ALL_SQL, false, INFO_ALL_VO_LIST);
            } catch (Exception ex) {
                LOGGER.error("批量插入cache_app_statistic_log_new失败～～～～", ex);
            }
            INFO_ALL_VO_LIST.clear();
        }
    }

    /**
     * 新增cache_instance_stat_new
     *
     * @param infoAllVo
     * @return
     */
    public static void insertInstanceInfoStat(InstanceInfoAllVo infoAllVo) {
        List<Object> params;
        if (infoAllVo != null) {
            params = new ArrayList<>();
            params.add(infoAllVo.getInstanceId());
            params.add(infoAllVo.getAppId());
            params.add(infoAllVo.getHostId());
            params.add(infoAllVo.getIp());
            params.add(infoAllVo.getPort());
            params.add(infoAllVo.getRole());
            params.add(infoAllVo.getMaxMem());
            params.add(infoAllVo.getUsedMem());
            params.add(infoAllVo.getKeyCount());
            params.add(infoAllVo.getCurrConnections());
            params.add(infoAllVo.getMisses());
            params.add(infoAllVo.getHits());
            params.add(infoAllVo.getMissesDiff());
            params.add(infoAllVo.getHitsDiff());
            params.add(infoAllVo.getLatestForkUsec());
            params.add(infoAllVo.getAofRewriteInProgress());
            params.add(infoAllVo.getAofLastRewriteTimeSec());
            params.add(infoAllVo.getBlockedClients());
            params.add(infoAllVo.getRdbLastBgsaveStatus());
            params.add(infoAllVo.getRdbLastSaveTime());
            params.add(infoAllVo.getClientInputBuf());
            params.add(infoAllVo.getClientOutputList());
            params.add(infoAllVo.getMasterLinkStatus());
            params.add(infoAllVo.getMasterLinkDownSinceSeconds());
            params.add(infoAllVo.getMasterLastIoSecondsAgo());
            params.add(infoAllVo.getConnectedSalves());
            params.add(infoAllVo.getSlaveLag());
            params.add(infoAllVo.getQps());
            params.add(infoAllVo.getHasExpireKeyCount());
            params.add(infoAllVo.getMemFragmentationRatio());
            params.add(new Date());
            params.add(BambooUtils.getDateFromUnixTime(infoAllVo.getCollectTime()));
            params.add(new Date());
            INFO_STAT_LIST.add(params);
        }
        if (INFO_STAT_LIST.size() == INFO_STAT_INT) {
            try {
                OzoMonitorJdbc.batchInsert(INSTANCE_STAT_SQL, false, INFO_STAT_LIST);
            } catch (Exception ex) {
                LOGGER.error("批量插入或者更新cache_instance_stat_new失败～～", ex);
            }
            INFO_STAT_LIST.clear();
        }
    }

    /**
     * 新增cache_instance_cmd_stat_new
     *
     * @param infoCmdVo
     * @return
     */
    public static void insertInstanceCmd(InstanceInfoCmdVo infoCmdVo) {
        List<Object> objects;
        if (infoCmdVo != null) {
            objects = new ArrayList<>();
            objects.add(infoCmdVo.getAppId());
            objects.add(infoCmdVo.getInstanceId());
            objects.add(infoCmdVo.getCommandName());
            objects.add(infoCmdVo.getCommandCount());
            objects.add(infoCmdVo.getCommandUsec());
            objects.add(infoCmdVo.getCommandType());
            objects.add(infoCmdVo.getCollectTime());
            objects.add(new Date());
            INFO_CMD_VO_LIST.add(objects);
        }
        if (INFO_CMD_VO_LIST.size() == CMD_INT) {
            try {
                OzoMonitorJdbc.batchInsert(CMD_STAT_SQL, false, INFO_CMD_VO_LIST);
            } catch (Exception ex) {
                LOGGER.error("批量插入cache_instance_cmd_stat_new数据失败～～～～", ex);
            }
            INFO_CMD_VO_LIST.clear();
        }
    }
}
